package com.fanco.learn_datastruct_leetcode.leetcode;

/**
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 * l1: 1 -> 2 -> 4
 * l2: 1 -> 3 -> 4
 * mergelist: 1 -> 1 -> 2 -> 3 -> 4 -> 4
 *
 * @author qiaowang 2021/7/6
 */


public class Day13 {
    public static void main(String[] args) {
        Solution solution = new Solution();

        ListNode l1 = new ListNode(1, new ListNode(2, new ListNode(4)));
        ListNode l2 = new ListNode(1, new ListNode(3, new ListNode(4)));

        ListNode listNode = solution.mergeTwoLists(l1, l2);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }

    }

    private static class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            // 创建一个空的头结点用来连接第一个节点。
            ListNode dummy = new ListNode(0);
            ListNode cur = dummy;

            /**
             * 遍历排序，l1 与 l2比较。
             */
            while (l1 != null && l2 != null) {
                int val1 = l1.val != 0 ? l1.val : 0;
                int val2 = l2.val != 0 ? l2.val : 0;

                if (val1 < val2) {
                    // l1 < l2
                    // l1后移再次重新比较
                    cur.next = l1;
                    cur = cur.next;
                    l1 = l1.next;
                } else {
                    // l1 >= l2
                    // l2后移再次重新比较
                    cur.next = l2;
                    cur = cur.next;
                    l2 = l2.next;
                }
            }

            // 极端情况考虑
            if (l1 == null) {
                cur.next = l2;
            } else {
                cur.next = l1;
            }

            return dummy.next;
        }
    }
}
